/**
 * Copyright 2015 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2015年9月10日 上午10:30:51
 */
package com.absir.appserv.system.service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import com.absir.appserv.configure.JConfigureUtils;
import com.absir.appserv.system.bean.JPayTrade;
import com.absir.appserv.system.bean.proxy.JiUserBase;
import com.absir.appserv.system.configure.JAnySdkConfigure;
import com.absir.appserv.system.helper.HelperClient;
import com.absir.appserv.system.helper.HelperJson;
import com.absir.bean.core.BeanFactoryUtils;
import com.absir.bean.inject.value.Bean;
import com.absir.core.kernel.KernelCharset;
import com.absir.core.kernel.KernelObject;
import com.absir.core.kernel.KernelString;
import com.absir.server.in.Input;

/**
 * @author absir
 *
 */
@Bean
public class AnySdkService implements IPayInterface, IdentityService {

	/** ME */
	public static final AnySdkService ME = BeanFactoryUtils.get(AnySdkService.class);

	/** ANY_SDK_CONFIGURE */
	public static final JAnySdkConfigure ANY_SDK_CONFIGURE = JConfigureUtils.getConfigure(JAnySdkConfigure.class);

	/** PLAT_FORM_NAME */
	public static final String PLAT_FORM_NAME = "AnySdk";

	/**
	 * anysdk统一登录地址
	 */
	protected String loginCheckUrl = "http://oauth.anysdk.com/api/User/LoginOauth/";

	/**
	 * user agent
	 * 
	 * @var string
	 */
	protected static final String userAgent = "px v1.0";

	/**
	 * @param input
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public boolean login(Input input) throws IOException {
		Map<String, ?> params = input.getParamMap();
		if (!(params.containsKey("channel") && params.containsKey("uapi_key") && params.containsKey("uapi_secret"))) {
			input.write("parameter not complete");
			return false;
		}

		params = HelperJson.buildParams(params);
		String post = KernelString.implode(params, '&', '=');
		HttpURLConnection urlConnection = (HttpURLConnection) (new URL(loginCheckUrl + '?' + post)).openConnection();
		byte[] postBytes = post.getBytes(KernelCharset.UTF8);
		urlConnection.setRequestProperty("User-Agent", userAgent);
		urlConnection.setRequestMethod("POST");
		urlConnection.addRequestProperty("Content-type", "text/plain");
		urlConnection.setDoOutput(true);
		urlConnection.connect();
		urlConnection.getOutputStream().write(postBytes, 0, postBytes.length);

		String result = HelperClient.openConnection(urlConnection, String.class);
		// System.out.println("loginAnySdk res = " + result);
		Map<String, Object> resultMap = HelperJson.decodeMap(result);
		boolean loginOK = false;
		if (IPlatformIdentity.PLATFORM_IDENTITY != null && KernelObject.equals("ok", resultMap.get("status"))) {
			Map<String, String> common = (Map<String, String>) resultMap.get("common");
			String uid = common.get("uid");
			String channel = common.get("channel");
			JiUserBase userBase = SecurityService.ME.openUserBase(uid, null, PLAT_FORM_NAME + "@" + channel);
			if (userBase != null) {
				String ext = IPlatformIdentity.PLATFORM_IDENTITY.loginPlatform(userBase);
				if (ext != null) {
					resultMap.put("ext", ext);
					result = HelperJson.encodeNull(resultMap);
				}
			}
		}

		input.write(result);
		return loginOK;
	}

	/**
	 * @author absir
	 *
	 */
	public static class LoginStatus {

		/** status */
		public String status;

		/** data */
		public LoginStatusData data;
	}

	/**
	 * @author absir
	 *
	 */
	public static class LoginStatusData {

		/** id */
		public String id;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.absir.appserv.system.service.IdentityService#getUserBase(java.lang
	 * .String[])
	 */
	@Override
	public JiUserBase getUserBase(String[] parameters) {
		if (parameters.length == 4) {
			return loginUserBase(parameters[1], parameters[2], parameters[3]);
		}

		return null;
	}

	/**
	 * @param channel
	 * @param uapi_key
	 * @param uapi_secret
	 * @return
	 */
	public JiUserBase loginUserBase(String channel, String uapi_key, String uapi_secret) {
		String queryString = "channel=" + channel + "&uapi_key=" + uapi_key + "&uapi_secret=" + uapi_secret;
		LoginStatus loginStatus = HelperClient.openConnection(loginCheckUrl, true, queryString.getBytes(KernelCharset.UTF8),
				LoginStatus.class);
		if (loginStatus != null && loginStatus.data != null && KernelObject.equals(loginStatus.status, "ok")) {
			String uid = loginStatus.data.id;
			if (uid != null) {
				return SecurityService.ME.openUserBase(uid, null, PLAT_FORM_NAME);
			}
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.absir.appserv.system.service.IPayInterface#validator(com.absir.appserv
	 * .system.bean.JPayTrade)
	 */
	@Override
	public boolean validator(JPayTrade payTrade) throws Exception {
		return false;
	}

}
